/**
  * 2023年十月巅峰赛活动相关数据的store，现复用于2024年五一活动
  * @author: Ruan Jiazhen
  * @date: 2024-04-29 10:25:25
* */

import { reqGet202310PersonalRankInfo, reqGet202310TeamInviteCompetitionInfo, reqGetPersonalPeakCompetitionScoreDetail, reqGetPersonalRankScoreChangeInfo, reqGetPersonInfo202310, reqGetRankingListBroadcast, reqGetTeamCheckInStatus, reqGetTeamInviteCompetitionScoreChangeInfo, reqGetTeamInviteCompetitionScoreDetail } from '@/api/activity-202310-api';
import { DEFAULT_PERSON_INFO } from '@/static/constant/202310-activity-constant';
import { randomId } from '@/utils/tools';
import { useUser } from './user';

/**
 * 原202310活动的store，现复用于2024年五一活动
 */

export const useActivity202310 = defineStore('activity202310', () => {
  const userStore = useUser();
  const { isLogin } = storeToRefs(userStore);
  // #region 个人信息相关
  /** 个人活动信息 */
  const personInfo202310 = ref(DEFAULT_PERSON_INFO);

  /** 获取个人信息 */
  const setPersonInfo202310 = async () => {
    const { data: { data: personInfoData } } = await reqGetPersonInfo202310();
    personInfo202310.value = {
      ...personInfo202310.value,
      userId: personInfoData.activityInfo.userId,
      avatar: personInfoData.activityInfo.avator,
      nickname: personInfoData.activityInfo.emcee_name,
      inviteKey: personInfoData.activityInfo.invite_key,
      isJoinTeam: personInfoData.activityInfo.teamId !== '',
    };
    console.log('personInfo202310', personInfo202310.value);
  };
  // #endregion

  // #region 个人巅峰赛排行榜相关

  /** 自己的个人巅峰赛数据 */
  const personalPeakCompetitionInfo = ref<PersonalPeakCompetitionInfo | undefined>(undefined);

  /** 个人巅峰赛排行榜数据 */
  const personalPeakCompetitionRankList = ref<PeakCompetitionRankItem[]>([]);

  /** 获取并设置个人巅峰赛数据 */
  const setPersonalPeakCompetitionRankList = async () => {
    const [
      { data: { data: personalRankInfoData } },
      { data: { data: personalRankScoreChangeInfoData } },
    ] = await Promise.all([
      reqGet202310PersonalRankInfo(),
      reqGetPersonalRankScoreChangeInfo(),
    ]);

    // 设置个人巅峰赛排行榜数据
    personalPeakCompetitionRankList.value = personalRankInfoData.list.map((item) => ({
      avatar: item.avator,
      nickname: item.emcee_name,
      reward: item.awardName,
      awardDetailsPopupImg: item.awardDetailsPopupImg,
    }));

    if (!isLogin.value) return;

    // 设置个人巅峰赛数据
    personalPeakCompetitionInfo.value = {
      score: personalRankInfoData?.myInfo?.miao_dou_all || 0,
      distance: personalRankInfoData.distance_miao_dou || 999,
      rank: Number(personalRankInfoData.myRank) || 0,
      todayScore: personalRankScoreChangeInfoData.today.change_dou,
      weekScore: personalRankScoreChangeInfoData.weed.change_dou,
    };
  };

  // #endregion

  // #region 个人巅峰赛积分明细相关

  /** 个人巅峰赛积分明细 */
  const personalPeakCompetitionScoreDetailList = ref<PeakCompetitionScoreDetailItem[]>([]);

  /** 分页数据 */
  const personalPeakCompetitionScoreDetailPagination = {
    page: 1,
    showCount: 10,
    total: 0,
  };

  /** 重置个人巅峰赛积分明细数据 */
  const resetPersonalPeakCompetitionScoreDetailList = () => {
    personalPeakCompetitionScoreDetailList.value = [];
    personalPeakCompetitionScoreDetailPagination.page = 1;
    personalPeakCompetitionScoreDetailPagination.total = 0;
  };

  /** 获取并追加个人巅峰赛积分明细数据 */
  // XXX 这个数据暂时不会频繁变动，所以不需要动态更新，只要直接在已有数据后追加即可
  const setPersonalPeakCompetitionScoreDetailList = async () => {
    if (personalPeakCompetitionScoreDetailList.value.length
      >= personalPeakCompetitionScoreDetailPagination.total
      && personalPeakCompetitionScoreDetailPagination.total !== 0) return;
    console.log('pagination', personalPeakCompetitionScoreDetailPagination);
    const {
      data: {
        data: {
          list,
          totalResult,
        },
      },
    } = await reqGetPersonalPeakCompetitionScoreDetail(
      personalPeakCompetitionScoreDetailPagination.page,
      personalPeakCompetitionScoreDetailPagination.showCount,
    );
    personalPeakCompetitionScoreDetailPagination.total = totalResult;

    if (!list) return;
    personalPeakCompetitionScoreDetailPagination.page += 1;

    personalPeakCompetitionScoreDetailList.value = [
      ...personalPeakCompetitionScoreDetailList.value,
      ...list.map((item) => ({
        id: randomId(),
        title: item.title,
        scoreText: `+${item.change_dou.toString()}`,
        time: item.send_time,
        flowText: item?.label || '',
      }))];
    console.log('personalPeakCompetitionScoreDetailList', personalPeakCompetitionScoreDetailList.value);
  };
  // #endregion

  // #region 团队邀请赛相关

  /** 自己的团队邀请赛数据 */
  const teamInviteCompetition = ref<TeamInviteCompetition | undefined>(undefined);

  /** 自己是否是队长 */
  const isTeamCaptain = computed(() => teamInviteCompetition.value?.teamMemberList
    .findIndex((item) => item.userId === personInfo202310.value?.userId) === 0);

  /** 团队邀请赛排行榜数据 */
  const teamInviteCompetitionRankList = ref<TeamInviteCompetitionRankItem[]>([]);

  // App任务完成情况
  const appTasks = ref<Array<{
    score: string;
    type: 'loginHaimiao' | 'publishWorks' | 'publishCircle' | 'createSchedule';
    title: string;
  }>>();

  /** 获取并设置团队邀请赛相关数据 */
  const setTeamInviteCompetitionData = async () => {
    const { data: { data: teamInviteCompetitionInfoData } } = (
      await reqGet202310TeamInviteCompetitionInfo()
    );
    // 设置App任务完成情况
    appTasks.value = teamInviteCompetitionInfoData.taskAppList;

    // 设置团队邀请赛排行榜数据
    teamInviteCompetitionRankList.value = teamInviteCompetitionInfoData.list.map((item) => ({
      avatar: item.icon,
      nickname: item.title,
      auth_status: item.auth_status,
      rewardList: item.awardName.map((reward) => ({
        icon: reward?.icon || '',
        title: reward.title || '',
      })),
    }));
    if (teamInviteCompetitionInfoData.isAddTeam !== '1') {
      teamInviteCompetition.value = undefined;
      return;
    }

    // 获取签到状态信息
    const [
      { data: { data: teamCheckInStatusData } },
      { data: { data: teamInviteCompetitionScoreChangeInfoData } },
    ] = await Promise.all([
      reqGetTeamCheckInStatus(),
      reqGetTeamInviteCompetitionScoreChangeInfo(),
    ]);

    // 设置自己的团队邀请赛数据
    teamInviteCompetition.value = {
      teamId: teamInviteCompetitionInfoData.teamInfo.teamId,
      teamAvatar: teamInviteCompetitionInfoData.teamInfo.icon,
      teamName: teamInviteCompetitionInfoData.teamInfo.title,
      score: teamInviteCompetitionInfoData.teamInfo.score,
      distance: teamInviteCompetitionInfoData.distance_score,
      auth_status: teamInviteCompetitionInfoData.teamInfo.auth_status,
      rank: Number(teamInviteCompetitionInfoData.myTeamRank),
      isCheckIn: teamCheckInStatusData?.signInStatus === '1',
      todayScore: teamInviteCompetitionScoreChangeInfoData.today.change_dou,
      weekScore: teamInviteCompetitionScoreChangeInfoData.weed.change_dou,
      teamMemberList: teamInviteCompetitionScoreChangeInfoData.teamMemberList
        .map((member) => ({
          userId: member.id,
          avatar: member.avator,
          nickname: member.emcee_name,
          score: member.teamScore,
        })),
    };
    console.log('008', teamInviteCompetition.value);
  };
  // #endregion

  // #region  团队邀请赛明细相关

  /** 团队邀请赛明细 */
  const teamInviteCompetitionScoreDetailList = ref<TeamInviteCompetitionScoreDetailItem[]>([]);

  /** 分页数据 */
  const teamInviteCompetitionScoreDetailPagination = {
    page: 1,
    showCount: 10,
    total: 0,
  };

  /** 重置团队邀请赛明细数据 */
  const resetTeamInviteCompetitionScoreDetailList = () => {
    teamInviteCompetitionScoreDetailList.value = [];
    teamInviteCompetitionScoreDetailPagination.page = 1;
    teamInviteCompetitionScoreDetailPagination.total = 0;
  };

  /** 获取并追加团队邀请赛明细数据 */
  // XXX 这个数据暂时不会频繁变动，所以不需要动态更新，只要直接在已有数据后追加即可
  const setTeamInviteCompetitionScoreDetailList = async () => {
    if (teamInviteCompetitionScoreDetailList.value.length
      >= teamInviteCompetitionScoreDetailPagination.total
      && teamInviteCompetitionScoreDetailPagination.total !== 0) return;

    const {
      data: {
        data: {
          list,
          totalResult,
        },
      },
    } = await reqGetTeamInviteCompetitionScoreDetail(
      teamInviteCompetitionScoreDetailPagination.page,
      teamInviteCompetitionScoreDetailPagination.showCount,
    );
    teamInviteCompetitionScoreDetailPagination.total = totalResult;

    if (!list) return;
    teamInviteCompetitionScoreDetailPagination.page += 1;

    teamInviteCompetitionScoreDetailList.value = [
      ...teamInviteCompetitionScoreDetailList.value,
      ...list.map((item) => ({
        id: randomId(),
        avatar: item.avator,
        nickname: item.emcee_name,
        title: item.title,
        scoreText: `${item.kind === '1' ? '+' : '-'}${item.change_dou.toString()}`,
        time: item.send_time,
        flowText: item?.label || '',
      }))];
  };

  // #endregion

  // #region 排行榜广播内容相关

  /** 个人巅峰赛排行榜广播内容 */
  const personalPeakCompetitionRankListBroadcastContent = ref<Array<{
    /** 头像 */
    avatar : string;
    /** 内容 */
    content : string | DanmuContent;
  }>>([]);

  /** 团队邀请赛排行榜广播内容 */
  const teamInviteCompetitionRankListBroadcastContent = ref<Array<{
    /** 头像 */
    avatar : string;
    name : string;
    score : string;
  }>>([]);

  /** 获取并设置排行榜广播内容 */
  const setRankListBroadcastContent = async () => {
    const { data: { data: rankListBroadcastData } } = await reqGetRankingListBroadcast();

    personalPeakCompetitionRankListBroadcastContent.value = rankListBroadcastData
      .personalPeakCompetitionBroadcastList;
    teamInviteCompetitionRankListBroadcastContent.value = rankListBroadcastData
      .teamInviteCompetitionBroadcastList;
  };

  return {
    personInfo202310,
    setPersonInfo202310,

    personalPeakCompetitionInfo,
    personalPeakCompetitionRankList,
    setPersonalPeakCompetitionRankList,

    personalPeakCompetitionScoreDetailList,
    personalPeakCompetitionScoreDetailPagination,
    resetPersonalPeakCompetitionScoreDetailList,
    setPersonalPeakCompetitionScoreDetailList,

    teamInviteCompetitionScoreDetailList,
    teamInviteCompetitionScoreDetailPagination,
    resetTeamInviteCompetitionScoreDetailList,
    setTeamInviteCompetitionScoreDetailList,

    teamInviteCompetition,
    isTeamCaptain,
    teamInviteCompetitionRankList,
    setTeamInviteCompetitionData,

    personalPeakCompetitionRankListBroadcastContent,
    teamInviteCompetitionRankListBroadcastContent,
    setRankListBroadcastContent,

    appTasks,
  };
});